package hotel.switchs.oversea.online.config;


import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/***
 * @Author: lmf
 * @Date: 2021/4/16
 */
@Component
public class RedisLockCommon {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //获取尝试时间
    private final long EXPIRE_TIME = 5 * 10000;

    /***
     * @Author: lmf
     * @Date: 2021/4/16
     * 加锁
     */
    public Boolean addLock(String key,String value){
        if (stringRedisTemplate.opsForValue().setIfAbsent(key, value, EXPIRE_TIME, TimeUnit.SECONDS)) {
            return true;
        }
        String currentValue=stringRedisTemplate.opsForValue().get(key);
        if(StringUtils.isNotEmpty(currentValue) && Long.parseLong(currentValue) <System.currentTimeMillis()){
            //获取上一个锁的时间 如果高并发的情况可能会出现已经被修改的问题  判断保证线程的安全
            String oldValue = stringRedisTemplate.opsForValue().getAndSet(key, value);
            if (StringUtils.isNotEmpty(oldValue) && oldValue.equals(currentValue)) {
                return true;
            }
        }
        return false;
    }

    /***
     * @Author: lmf
     * @Date: 2021/4/16
     * 解锁
     */
    public void unLock(String key,String value){
        String currentValue=stringRedisTemplate.opsForValue().get(key);
        try{
            if(StringUtils.isNotEmpty(currentValue)&&currentValue.equals(value)){
                stringRedisTemplate.opsForValue().getOperations().delete(key);
            }
        }catch (Exception e){

        }
    }
}
